package org.shiki.hrm.config;

import org.shiki.hrm.authenhandle.MyAuthenFail;
import org.shiki.hrm.authenhandle.MyAuthenSuccess;
import org.shiki.hrm.detail.MyUserDatailService;
import org.shiki.hrm.filter.SmsCodeAuthenticationFilter;
import org.shiki.hrm.filter.SmsCodeProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

//security 的配置
@Configuration
@EnableWebSecurity  //开启Security
public class SmsAuthConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private MyUserDatailService myUserDetailsService ;

    @Autowired
    private MyAuthenFail myAuthenticationFailureHandler;

    @Autowired
    private MyAuthenSuccess myAuthenticationSuccessHandler;

    @Override
    public  void configure(HttpSecurity http) throws Exception {

        //短信认证Filter
        SmsCodeAuthenticationFilter smsAuthFilter = new SmsCodeAuthenticationFilter();
        smsAuthFilter.setAuthenticationSuccessHandler(myAuthenticationSuccessHandler);
        smsAuthFilter.setAuthenticationFailureHandler(myAuthenticationFailureHandler);

        smsAuthFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));

        //短信认证provider
        SmsCodeProvider smsDaoAuthenticationProvider = new SmsCodeProvider();
        smsDaoAuthenticationProvider.setUserDetailsService(myUserDetailsService);


        //添加短信认证provider
        http.authenticationProvider(smsDaoAuthenticationProvider);
        //添加短信认证filter
        http.addFilterAfter(smsAuthFilter, UsernamePasswordAuthenticationFilter.class);

    }
}